/**
 * Created by TomSean on 2017/3/21.
 */
var PreferentialPolicyManager = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
};
PreferentialPolicyManager.prototype = {
    init : function() {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : "search_btn", fs : this.findData},
            {fName : "reset_btn", fs : this.resetInfo}
        ];
        this.bindBaseModels = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        this.createList();
        this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
    },
    createList : function() {
        var _this = this;
        var columns = [
            {
                width : 30,
                headerTemplate : '<input type="checkbox" gridId="policy_data_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="policiesCode" value="${policiesCode}" />'
            },
            {
                title : '策划编号',
                field : 'policiesCode'
            },
            {
                title : '策划名称',
                field : 'policiesName'
            },
            {
                title : '创建人',
                field : 'createUser'
            },
            {
                title : '创建时间',
                field : 'createTime'
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#policy_data_list'), {
            selectable : 'single',
            autoSync : true,
            columnMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function() {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find("input[type=checkbox]").val();
                });
                _this.selectRowId = selected[0];
            },
            dataBound : function() {
                var $list = _this.$parent.find("#policy_data_list");
                $list.find("tr").unbind("dblclick");
                $list.find("tr").dblclick(function(e){
                    var grid = $list.data("kendoGrid");
                    var dataItem = grid.dataItem(grid.select());
                    //打开查看窗口
                    _this.isEdit = false;
                    _this.checkData(dataItem["policiesCode"]);
                });
            }
        });
    },
    checkData :function(id) {
        var _this = this;
        JsonpAjax(baseApiPath + "policy/one/" + id, undefined, 'json', function(res) {
            _this.entity = res;
            _this.editWindow = _this.sysUtils.openWindow(_this.editWindow, {
                title : "查看优惠策略",
                height : "660px",
                width : "950px",
                resizable : false,
                content : "views/parkLotCenter/discountManage/preferentialPolicy_edit.html"
            });
        });
    },
    findData : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var params = _this.sysUtils.getBindDocJson(_this.bindBaseModels.bindFieldArray);
        var dataT = {jsonParam : JSON.stringify(params)};
        var dataSource = _this.sysUtils.getDataSource({
            url : baseApiPath + 'policy/list',
            data : dataT,
            dataType : 'odata'
        });
        var grid = _this.$parent.find('#policy_data_list').data('kendoGrid');
        grid.setDataSource(dataSource);
    },
    openNewWindow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.entity = undefined;
        _this.editWindow = _this.sysUtils.openWindow(_this.editWindow, {
            title : "新增优惠策略",
            height : "655px",
            width : "950px",
            resizable : false,
            content : "views/parkLotCenter/discountManage/preferentialPolicy_edit.html"
        });
    },
    openEditWindow : function(e) {
        var _this = this;
        _this.isEdit = true;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (isEmpty(_this.selectRowId)) {
            notification({title : '操作失败', message : '请选择您需要修改的数据'}, 'info');
            return;
        }
        JsonpAjax(baseApiPath + "policy/one/" + _this.selectRowId, undefined, 'json', function(res) {
            _this.entity = res;
            _this.editWindow = _this.sysUtils.openWindow(_this.editWindow, {
                title : "编辑优惠策略",
                height : "655px",
                width : "950px",
                resizable : false,
                content : "views/parkLotCenter/discountManage/preferentialPolicy_edit.html"
            });
        });
    },
    deletePolicy : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        notification({title : '请确认', message : '删除后将解绑该策略名下的所有优惠项目，这些项目在再次绑定前将无法使用，是否确认删除？'}, 'confirm', {
            callback : function() {
                var ids = "";
                _this.$parent.find('input[type=checkbox]:checked').each(function(inx, itm){
                    ids += $(itm).val()+",";
                });
                if (ids == "") {
                    notification({title : '失败', message : '删除前请至少选择一项'}, 'info');
                    return "";
                }
                ids = ids.substring(0, ids.length - 1);
                JsonpAjax(baseApiPath + "policy/delete?ids="+ids, undefined, "json", function(res) {
                    _this.findData();

                });
            }
        })
    }
};

var PreferentialPolicyEdit = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.sourceDataMap = new Map();       //原始数据数据
    this.compontDataMap = new Map();      //组合优惠数据
    this.singleDataMap = new Map();       //独立使用数据
    policyManager.indexRow = 0;
    this.init();
    return this;
};
PreferentialPolicyEdit.prototype = {
    init : function() {
        var $this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        fieldArray.push({fieldName:"preferentDataList",defaultValue:[]});
        fieldArray.push({fieldName:"policyGroupDataList",defaultValue:[]});
        fieldArray.push({fieldName : "policyIndependentDataList", defaultValue:[]});

        var functionArray = [
            {fName : "save_btn", fs : this.saveInfo},
            {fName : "search_preferential", fs : this.searchPreferential},
            {fName : "add_group_btn", fs : this.addGroup},
            {fName : "add_independent_btn", fs : this.addIndependent},
            {fName : "cancel", fs : function () {$('#'+policyManager.editWindow).data('kendoWindow').close();} }
        ];
        this.bindBaseModels = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        this.sysUtils.setBindFieldValue(policyManager.entity);

        // 获取商家信息
        JsonpAjax(baseApiPath + 'merchant/interface/dropdown', '','json', function(res) {
            var merchants = $this.$parent.find('#merchantId').kendoDropDownList({
                dataTextField : "merchantName",
                dataValueField : "id",
                dataSource : res
            }).data('kendoDropDownList');
        }, false);

        this.createList();
        this.searchPreferential();

        policyManager.indexRow = 0;
        if (!isEmpty(policyManager.entity) && !isEmpty(policyManager.entity.compont)) {
            for (var i = 0; i < policyManager.entity.compont.length; i++) {
                this.compontDataMap.put(policyManager.entity.compont[i].preferentialCode, policyManager.entity.compont[i]);
            }
        }


        this.sysUtils.mvvmModel.set("policyGroupDataList", this.compontDataMap.values());
        policyManager.indexRow = 0;
        if (!isEmpty(policyManager.entity) && !isEmpty(policyManager.entity.single)) {
            for (var i = 0; i < policyManager.entity.single.length; i++) {
                this.singleDataMap.put(policyManager.entity.single[i].preferentialCode, policyManager.entity.single[i]);
            }
        }
        this.sysUtils.mvvmModel.set("policyIndependentDataList", this.singleDataMap.values());
        if (false == policyManager.isEdit) {
            this.$parent.find("input[type]").attr("disabled","disabled");
            this.$parent.find("select").attr("disabled","disabled");
            this.$parent.find("textarea").attr("disabled","disabled");
            this.$parent.find('.save').remove();
        }
    },
    saveInfo : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var params = _this.sysUtils.getBindDocJson();
        var dataT = {params:JSON.stringify(params)};
        JsonpAjax(baseApiPath + 'policy/save', dataT, 'json', function(res) {
            policyManager.findData();
            $('#'+policyManager.editWindow).data('kendoWindow').close();
        });
    },
    searchPreferential : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var params = _this.sysUtils.getBindDocJson(_this.bindBaseModels.bindFieldArray);
        if (!isEmpty(params["beginTime"])) params["beginTime"] = params["beginTime"].pattern("yyyy-MM-dd");
        if (!isEmpty(params["endTime"])) params["endTime"] = params["endTime"].pattern("yyyy-MM-dd");
        params['merchantId'] = _this.$parent.find('#merchantId').val();
        new JsonpAjax(baseApiPath + 'preferential/listByJsonp',JSON.stringify(params),"jsonp",function(data){
            for(var i = 0; i < data.length ; i++){
                _this.sourceDataMap.put(data[i]["preferentialCode"],data[i]);
            }
            _this.sysUtils.mvvmModel.set("preferentDataList",data);
        });

    },
    createList : function() {
        var _this = this;
        var columns = [
            {
                title : "优惠项目",
                field : "preferentialName"
            },
            {
                title : "优惠方式",
                template : "#:Utils.getModelNameByParentKey(BASIS.PREFERENTIAL_TYPE.ROOT, preferentialType)#"
            },
            {
                title : "优惠值",
                field : "preferentialContent"
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#preferential_data_list'), {
            selectable : 'multiple',
            autoSync : true,
            columnMenu : true,
            columns : columns
        });
        columns = [
            {
                title : "优惠项目",
                field : "preferentialName"
            },
            {
                title : "操作",
                template : "" +
                "<a onclick=\"policyEdit.moveToTopFromGroup('#:preferentialCode#')\">上移</a>&nbsp;&nbsp;" +
                "<a onclick=\"policyEdit.moveToDownFromGroup('#:preferentialCode#')\">下移</a>&nbsp;&nbsp;" +
                "<a onclick=\"policyEdit.removeGroupToSource('#:preferentialCode#')\">删除</a>"
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#policy_group_item'), {
            autoSync : true,
            columnMenu : true,
            columns : columns
        });
        columns = [
            {
                title : "优惠项目",
                field : "preferentialName"
            },
            {
                title : "操作",
                template : "" +
                "<a onclick=\"policyEdit.moveToTopFromGroup('#:preferentialCode#')\">上移</a>&nbsp;&nbsp;" +
                "<a onclick=\"policyEdit.moveToDownFromGroup('#:preferentialCode#')\">下移</a>&nbsp;&nbsp;" +
                "<a onclick=\"policyEdit.removeSingleToSource('#:preferentialCode#')\">删除</a>"
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#policy_independent_item'), {
            autoSync : true,
            columnMenu : true,
            columns : columns
        });

    },
    removeGroupToSource:function(code){
        var codeList = new Array();
        codeList.push(code);
        this.moveDataSourceToTarget(codeList,this.compontDataMap,this.sourceDataMap,"policyGroupDataList", "preferentDataList");
    },
    removeSingleToSource:function(code){
        var codeList = new Array();
        codeList.push(code);
        this.moveDataSourceToTarget(codeList,this.singleDataMap,this.sourceDataMap,"policyIndependentDataList", "preferentDataList");
    },
    /**
     * 移除组合列表到原始列表
     * @param e
     */
    moveDataSourceToTarget:function(codeList,source,target,sourceName,targetName){
        var dataObj = null;
        for(var i = 0 ; i < codeList.length; i ++ ){
            dataObj = source.get(codeList[i]);
            target.put(codeList[i],dataObj);
            source.remove(codeList[i]);
        }
        policyManager.indexRow = 0;
        this.sysUtils.mvvmModel.set(sourceName,source.values());
        policyManager.indexRow = 0;
        this.sysUtils.mvvmModel.set(targetName,target.values());
    },
    /* 添加到组合 */
    addGroup : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
            if(isEmpty(_this)){
                _this = $(e.target).parent().data('that');
            }
        }
        var dataList = _this.$parent.find("#preferential_data_list").data("kendoGrid");
        var selectRow = dataList.select();
        var codeList = new Array();
        for(var i = 0;i < selectRow.length; i++){
            var preferentialCode = dataList.dataItem(selectRow[i])["preferentialCode"];
            codeList.push(preferentialCode);
        }
        _this.moveDataSourceToTarget(codeList,_this.sourceDataMap,_this.compontDataMap,"preferentDataList","policyGroupDataList");
    },
    /* 添加到独立项 */
    addIndependent : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
            if(isEmpty(_this)){
                _this = $(e.target).parent().data('that');
            }
        }
        var dataList = _this.$parent.find("#preferential_data_list").data("kendoGrid");
        var selectRow = dataList.select();
        var codeList = new Array();
        for(var i = 0;i < selectRow.length; i++){
            var preferentialCode = dataList.dataItem(selectRow[i])["preferentialCode"];
            codeList.push(preferentialCode);
        }
        _this.moveDataSourceToTarget(codeList,_this.sourceDataMap,_this.singleDataMap,"preferentDataList","policyIndependentDataList");
    },
    moveToTopFromGroup : function(key) {
        this.compontDataMap.elementMove(key, 1);
        this.sysUtils.mvvmModel.set('policyGroupDataList', this.compontDataMap.values());
    },
    moveToDownFromGroup : function(key) {
        this.compontDataMap.elementMove(key, -1);
        this.sysUtils.mvvmModel.set('policyGroupDataList', this.compontDataMap.values());
    }
};